<?php

namespace App\Http\Controllers\Admin\Personnel;

use App\Http\Controllers\Controller;
use App\Models\AdminAuthModel;
use App\Models\AdminModel;
use App\Models\StaffModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class Admin extends Controller
{

    public function index(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $staff_name = $request->input('staff_name', '');
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');

        $query = AdminModel::query()->whereHas('staff', function($query) use ($staff_name) {
            if($staff_name){
                $query->where('name', 'like', "%{$staff_name}%");
            }
        });

        if($create_start && $create_end){
            $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->orderBy('id','desc')
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($v) {
            $auth = json_decode($v->auth);
            if($v->auth == '*') {
                $auth = AdminAuthModel::pluck('id');
            }
            $res = [
                'id' => $v->id,
                'account' => $v->account,
                'staff_id' => $v->staff_id,
                'staff_name' => $v->staff->name ?? '',
                'dept_name' => $v->staff->dept->name ?? '',
                'dept_id' => $v->dept_id,
                'role' => $v->staff->role->name ?? '',
                'auth' => $auth,
                'status' => $v->status,
                'created_at' => $v->created_at->toDateTimeString(),
                'create_user' => $v->create_admin->staff->name ?? '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request){
        $auth_login = $request->get('auth');
        $params = $request->all();
        $validator = Validator::make($params, [
            'staff_id' => 'required|integer',
            'dept_id' => 'required|integer',
            'account' => 'required',
        ], [
            'account.required' => '请填写账号',
            'dept_id.required' => '请选择关联部门',
            'staff_id.required' => '请选择关联员工',
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $pattern = '/^[a-zA-Z0-9]+$/';
        if (!preg_match($pattern, $params['account'])) {
            return $this->error('账号只能输入数字+字母的组合');
        }

        $e = AdminModel::where('account', trim($params['account']))->first();
        if($e) {
            return $this->error('账号已存在');
        }

        $password = $params['password'] ?? '123456';

        $auth = isset($params['auth']) ? $params['auth'] : [];

        $admin = new AdminModel();
        $admin->staff_id = $params['staff_id'];
        $admin->dept_id = $params['dept_id'];
        $admin->account = trim($params['account']);
        $admin->password = password_hash($password, PASSWORD_DEFAULT);
        $admin->auth = json_encode($auth);
        $admin->created_admin_id = $auth_login->id;
        $admin->save();

        return $this->success();
    }

    public function update(Request $request, int $id){
//        $auth = $request->get('auth');
        $params = $request->all();
        $validator = Validator::make($params, [
            'staff_id' => 'required|integer',
            'account' => 'required',
            'dept_id' => 'required|integer'
        ], [
            'account.required' => '请填写账号',
            'staff_id.required' => '请选择关联员工',
            'dept_id.required' => '请选择关联部门',
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $admin = AdminModel::find($id);
        if(!$admin) {
            return $this->error('账号异常');
        }
        if($admin->account == 'admin') {
            return $this->error('不能修改系统管理员');
        }

        $e = AdminModel::where('account', trim($params['account']))
            ->where('id', '<>', $id)->first();
        if($e) {
            return $this->error('账号已存在');
        }

        $password = $params['password'] ?? '';
        if(!empty($password)) {
            $admin->password = password_hash($password, PASSWORD_DEFAULT);
        }

        $auth = isset($params['auth']) ? $params['auth'] : [];

        $admin->account = trim($params['account']);
        $admin->staff_id = $params['staff_id'];
        $admin->dept_id = $params['dept_id'];
        $admin->auth = json_encode($auth);
        $admin->save();

        return $this->success();
    }

    public function delete(Request $request, int $id){
        $admin = AdminModel::find($id);
        if(!$admin) {
            return $this->error('账号异常');
        }
        if($admin->account == 'admin') {
            return $this->error('不能删除系统管理员');
        }
        $admin->delete();
        return $this->success();
    }

    public function modify_password(Request $request) {
        $auth = $request->get('auth');

        $old = $request->input('origin_password', '');
        $password = $request->input('password', '');

        if(empty($old)) {
            return $this->error('请出入原密码');
        }

        $admin = AdminModel::find($auth->id);

        if(!password_verify($old, $admin->password)){
            return $this->error("原密码错误");
        }

        $admin->password = password_hash($password, PASSWORD_DEFAULT);
        $admin->save();

        return $this->success();

    }

    /**
     * Notes:账号禁用启状态用切换
     * User: xiangzi
     * Date: 2025/3/26
     * Time: 下午2:30
     * @return \Illuminate\Http\JsonResponse
     */
    public function status(Request $request, $id) {
        $params = $request->all();
        if(!isset($params['status'])){
            return $this->error('缺少状态参数');
        }

        $admin = AdminModel::find($id);
        if(!$admin) {
            return $this->error('账号异常');
        }

        $admin->status = $params['status'];
        $admin->save();

        return $this->success();
    }

    /**
     * Notes:获取员工手机号
     * User: xiangzi
     * Date: 2025/3/26
     * Time: 下午2:30
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_staff_phone(Request $request) {
        $auth = $request->get('auth');
        $staff_id = $request->input('id', '');

        $staff = StaffModel::find($staff_id);
        if(!$staff) {
            return $this->error('员工不存在');
        }

        return $this->success(['phone' => $staff->phone]);
    }

}
